package com.singfan.app.controller;

import com.singfan.app.controller.model.HttpModelConverter;
import com.singfan.app.controller.model.request.ShopDetailRequest;
import com.singfan.app.controller.model.request.ShopListRequest;
import com.singfan.app.controller.model.response.ResultCode;
import com.singfan.app.controller.model.response.ShopDetailResponse;
import com.singfan.app.controller.model.response.ShopListResponse;
import com.singfan.app.controller.model.response.partial.BarberPartial;
import com.singfan.app.controller.model.response.partial.LocationPartial;
import com.singfan.app.controller.model.response.partial.PriceMenuItemPartial;
import com.singfan.app.controller.model.response.partial.ShopSummaryPartial;
import com.singfan.app.util.RequestParamChecker;
import com.singfan.common.util.GPSUtil;
import com.singfan.common.util.StringUtil;
import com.singfan.core.component.CustomerTokenHolder;
import com.singfan.core.dao.database.model.*;
import com.singfan.core.dao.database.model.constant.CollectType;
import com.singfan.core.dao.database.model.constant.FilterType;
import com.singfan.core.dao.database.model.constant.HairServiceType;
import com.singfan.core.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * Author: hansonghe
 * Date: 2015-08-24 11:15
 * Desc:
 */
@Controller
public class ShopController extends SingFanControllerBase {
    @Autowired
    private IShopService shopService;

    @RequestMapping(value="/v1/shop/list", method= RequestMethod.POST)
    public void list(HttpServletRequest request, HttpServletResponse response){
        ShopListResponse shopListResponse = new ShopListResponse();
        ShopListRequest shopListRequest = request2Bean(request, ShopListRequest.class);

        boolean checkResult = true;

        String ip = getIpAddress(request);
        String accessToken = shopListRequest.getAccessToken();
        int serviceType = shopListRequest.getServiceType();
        int listOrderType = shopListRequest.getListOrderType();
        int cityId = shopListRequest.getCityId();
        int businessCircleId = shopListRequest.getBusinessCircleId();
        int pageIndex = shopListRequest.getPageIndex();
        int pageSize = shopListRequest.getPageSize();
        int dayTime = shopListRequest.getDayTime();
        int clockTime = shopListRequest.getClockTime();
        String longitudeText = shopListRequest.getLongitude();
        String latitudeText = shopListRequest.getLatitude();

        if (!HairServiceType.isHairServiceType(serviceType)){
            checkResult = false;
        }
        else if(!FilterType.isFilterType(listOrderType)){
            checkResult = false;
        }
        else if (!RequestParamChecker.checkLongitude(longitudeText)){
            checkResult = false;
        }
        else if (!RequestParamChecker.checkLatitude(latitudeText)){
            checkResult = false;
        }
        else if(!RequestParamChecker.checkPageIndexAndSize(pageIndex, pageSize)){
            checkResult = false;
        }

        double longitude = Double.parseDouble(longitudeText);
        double latitude = Double.parseDouble(latitudeText);

        if (checkResult){
            shopListResponse.setResultCode(ResultCode.SUCCESS);
            List<ShopHair> shopHairList = shopService.findShopHairList(shopListRequest.getServiceType(), shopListRequest.getListOrderType(), shopListRequest.getCityId(), shopListRequest.getBusinessCircleId(), longitude, latitude, shopListRequest.getPageIndex(), shopListRequest.getPageSize());
            if (shopListRequest.getPageIndex() == 0){
                shopListResponse.setNewList(true);
            }
            List<ShopSummaryPartial> shopSummaryPartialList = new ArrayList<>(shopHairList.size());
            for (ShopHair shopHair : shopHairList){
                ShopSummaryPartial shopSummaryPartial = HttpModelConverter.shopHair2ShopSummaryPartial(shopHair);
                int distance = GPSUtil.getDistance(longitude, latitude, shopHair.getLongitude().doubleValue(), shopHair.getLatitude().doubleValue());
                shopSummaryPartial.setDistance(distance);

                shopSummaryPartialList.add(shopSummaryPartial);
            }

            if (shopListRequest.getListOrderType() == FilterType.DISTANCE) {
                java.util.Collections.sort(shopSummaryPartialList, new Comparator(){
                    @Override
                    public int compare(Object o1, Object o2) {
                        ShopSummaryPartial shopSummaryPartial1 = (ShopSummaryPartial)o1;
                        ShopSummaryPartial shopSummaryPartial2 = (ShopSummaryPartial)o2;
                        return shopSummaryPartial1.getDistance() - shopSummaryPartial2.getDistance();
                    }
                });
            }
            shopListResponse.setShopList(shopSummaryPartialList);

            traceLog.debug(String.format("ShopController.list() successful -> resultCode:%1$d, ip:%2$s, accessToken:%3$s, serviceType:%4$d, listOrderType:%5$d, cityId:%6$d, businessCircleId:%7$d, pageIndex:%8$d, pageSize:%9$d, dayTime:%10$d, clockTime:%11$d, longitude:%12$s, latitude:%13$s", ResultCode.SUCCESS, ip, accessToken, serviceType, listOrderType, cityId, businessCircleId, pageIndex, pageSize, dayTime, clockTime, longitudeText, latitudeText));
        }
        else {
            shopListResponse.setResultCode(ResultCode.REQUEST_PARAM_ERROR);

            traceLog.error(String.format("ShopController.list() error with REQUEST_PARAM_ERROR -> resultCode:%1$d, ip:%2$s, accessToken:%3$s, serviceType:%4$d, listOrderType:%5$d, cityId:%6$d, businessCircleId:%7$d, pageIndex:%8$d, pageSize:%9$d, dayTime:%10$d, clockTime:%11$d, longitude:%12$s, latitude:%13$s", ResultCode.REQUEST_PARAM_ERROR, ip, accessToken, serviceType, listOrderType, cityId, businessCircleId, pageIndex, pageSize, dayTime, clockTime, longitudeText, latitudeText));
        }

        bean2Response(response, shopListResponse);
    }

    @RequestMapping(value="/v1/shop/detail", method= RequestMethod.POST)
    public void detail(HttpServletRequest request, HttpServletResponse response){
        ShopDetailResponse shopDetailResponse = new ShopDetailResponse();
        ShopDetailRequest shopDetailRequest = request2Bean(request, ShopDetailRequest.class);

        boolean checkResult = true;

        String ip = getIpAddress(request);
        String accessToken = shopDetailRequest.getAccessToken();
        long shopId = shopDetailRequest.getShopId();
        int serviceType = shopDetailRequest.getServiceType();
        String longitudeText = shopDetailRequest.getLongitude();
        String latitudeText = shopDetailRequest.getLatitude();
        int dayTime = shopDetailRequest.getDayTime();
        int clockTime = shopDetailRequest.getClockTime();

        if (!RequestParamChecker.checkLongitude(longitudeText)){
            checkResult = false;
        }
        else if (!RequestParamChecker.checkLatitude(latitudeText)){
            checkResult = false;
        }

        if (checkResult){
            double longitude = Double.parseDouble(longitudeText);
            double latitude = Double.parseDouble(latitudeText);

            ShopHair shopHair = shopService.findShopHair(shopId);
            if (shopHair != null){
                Shop shop = shopService.findShop(shopId);

                shopDetailResponse.setResultCode(ResultCode.SUCCESS);
                List<String> imgUrlList = StringUtil.split(shopHair.getImgList(), ";");
                shopDetailResponse.setShopImgUrlList(imgUrlList);
                shopDetailResponse.setShopMasterName(shopHair.getMasterShopName());
                shopDetailResponse.setShopSlaveName(shopHair.getSlaveShopName());
                shopDetailResponse.setShopDesc(shopHair.getDescription());
                LocationPartial locationPartial = new LocationPartial();
                locationPartial.setAddressText(shopHair.getAddress());
                locationPartial.setShopMasterName(shopHair.getMasterShopName());
                locationPartial.setShopSlaveName(shopHair.getSlaveShopName());
                locationPartial.setLongitude(String.valueOf(shopHair.getLongitude()));
                locationPartial.setLatitude(String.valueOf(shopHair.getLatitude()));
                shopDetailResponse.setShopLocation(locationPartial);
                shopDetailResponse.setShopTelNum(shop.getContactNumber());
                long customerId = 0;
                CustomerToken customerToken = CustomerTokenHolder.getCurrentCustomerToken();
                if (customerToken != null){
                    customerId = customerToken.getCustomerId();
                }

                if (customerId > 0){
                    boolean isCollected = customerService.isCollected(customerId, shopId, CollectType.SHOP);
                    shopDetailResponse.setCollected(isCollected);
                }
                else {
                    shopDetailResponse.setCollected(false);
                }

                List<ShopHairService> shopHairServiceList = shopService.selectShopHairServiceList(shopId);
                List<PriceMenuItemPartial> priceMenuItemPartialList = new ArrayList<>(shopHairServiceList.size());
                for (ShopHairService shopHairService : shopHairServiceList){
                    PriceMenuItemPartial itemPartial = new PriceMenuItemPartial();

                    itemPartial.setItemType(shopHairService.getServiceType());
                    itemPartial.setItemID(shopHairService.getId());
                    itemPartial.setItemName(shopHairService.getServiceName());
                    itemPartial.setOriginalPrice(shopHairService.getOriginalPrice());
                    itemPartial.setCurrentPrice(shopHairService.getRealPrice());

                    priceMenuItemPartialList.add(itemPartial);
                }
                shopDetailResponse.setPriceMenu(priceMenuItemPartialList);

                List<Barber> barberList = barberService.selectBarberListByShopId(shopId, serviceType, dayTime, clockTime);
                List<BarberPartial> barberPartialList = new ArrayList<>(barberList.size());
                int distance = GPSUtil.getDistance(longitude, latitude, shop.getLongitude().doubleValue(), shop.getLatitude().doubleValue());
                for (Barber barber : barberList){
                    BarberPartial barberPartial = HttpModelConverter.barber2BarberPartial(barber);
                    barberPartial.setDistance(distance);
                    barberPartialList.add(barberPartial);
                }
                shopDetailResponse.setBarberList(barberPartialList);

                traceLog.error(String.format("ShopController.detail() successful -> resultCode:%1$d, ip:%2$s, accessToken:%3$s, shopId:%4$d, serviceType:%5$d, longitude:%6$s, latitude:%7$s, dayTime:%8$d, clockTime:%9$d", ResultCode.SUCCESS, ip, accessToken, shopId, serviceType, longitudeText, latitudeText, dayTime, clockTime));
            }
            else {
                shopDetailResponse.setResultCode(ResultCode.REQUEST_PARAM_ERROR);

                traceLog.error(String.format("ShopController.detail() error with REQUEST_PARAM_ERROR -> resultCode:%1$d, ip:%2$s, accessToken:%3$s, shopId:%4$d, serviceType:%5$d, longitude:%6$s, latitude:%7$s, dayTime:%8$d, clockTime:%9$d", ResultCode.REQUEST_PARAM_ERROR, ip, accessToken, shopId, serviceType, longitudeText, latitudeText, dayTime, clockTime));
            }
        }
        else {
            shopDetailResponse.setResultCode(ResultCode.REQUEST_PARAM_ERROR);

            traceLog.error(String.format("ShopController.detail() error with REQUEST_PARAM_ERROR -> resultCode:%1$d, ip:%2$s, accessToken:%3$s, shopId:%4$d, serviceType:%5$d, longitude:%6$s, latitude:%7$s, dayTime:%8$d, clockTime:%9$d", ResultCode.REQUEST_PARAM_ERROR, ip, accessToken, shopId, serviceType, longitudeText, latitudeText, dayTime, clockTime));
        }

        bean2Response(response, shopDetailResponse);
    }
}
